#include <my_header.h>
#include <openssl/sha.h>
#include <openssl/evp.h>

/* Usage:  */
int main(void){
    int fd = open("a.txt", O_RDONLY);
    ERROR_CHECK(fd, -1, "open");
    char buff[1000] = {0};
    int ret = 0;

    //使用EVP接口
    EVP_MD_CTX* context = EVP_MD_CTX_new();
    ERROR_CHECK(context, NULL, "EVP_MD_CTX_new");

    //初始化sha_256
    EVP_DigestInit_ex(context, EVP_sha256(), NULL);

    while(1){
        bzero(&buff, sizeof(buff));
        ret = read(fd, buff, sizeof(buff));
        if(ret == 0){
            break;
        }
        //每段内容都需要调用更新函数
        EVP_DigestUpdate(context, buff, ret);
    }

    unsigned length = 0;
    unsigned char sh[SHA256_DIGEST_LENGTH] = {0};
    EVP_DigestFinal_ex(context, sh, &length);

    char result[32] = {0};
    for(unsigned int i = 0; i < length; i++){
        char frag[3] = {0};
        sprintf(frag, "%02x", sh[i]);
        strcat(result, frag);
    }

    printf("result:%s\n", result);

    //释放资源
    EVP_MD_CTX_free(context);

    return 0;
}

